package cn.rocksolid.sport.security.service.impl;

import cn.rocksolid.sport.common.Constant.AccessType;
import cn.rocksolid.sport.common.utils.CodecUtils;
import cn.rocksolid.sport.common.utils.Guid;
import cn.rocksolid.sport.security.dao.TokenDao;
import cn.rocksolid.sport.security.entity.TokenEntity;
import cn.rocksolid.sport.security.service.TokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * System access token service implementation
 *
 * @author Axl Zhao
 * @email axl.zhao@163.com
 */
@Service
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {

  @Override
  @Transactional(rollbackFor = Exception.class)
  public String create(final String accessId, final AccessType accessType, final int seconds) {
    TokenEntity tokenEntity = new TokenEntity();
    tokenEntity.setId(CodecUtils.md5(Guid.random()));
    tokenEntity.setAccessId(accessId);
    tokenEntity.setAccessType(accessType);
    tokenEntity.setExpireTime(DateUtils.addSeconds(new Date(), seconds));
    this.save(tokenEntity);
    return tokenEntity.getId();
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void destroy(final String accessToken, final String accessId, final AccessType accessType) {
    TokenEntity tokenEntity = this.getById(accessToken);
    if (null == tokenEntity) {
      return;
    }
    this.removeById(accessToken);
  }

  @Override
  public TokenEntity lookup(final String accessToken) {
    return this.getById(accessToken);
  }
}
